import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useDesign = defineStore('drag', () => {
	const componentList = ref([])
	const componentIndex = ref(undefined)
	const widgetFormConfig: any = ref({})
	const setActive = (index) => {
		componentIndex.value = index
	}
	const deleteDesign = () => {
		componentList.value.splice(componentIndex.value, 1)
	}

	const setWidgetFormConfig = (obj) => {
		widgetFormConfig.value = obj
	}
	const setDesignData = (arr) => {
		componentList.value = arr
	}

	const setDrop = (ev, key = 'component') => {
		ev.preventDefault()
		const data = ev.dataTransfer.getData(key)
		const indexKey = componentList.value.length + 1
		componentList.value.unshift({
			refreshKey: 0,
			x: 0,
			y: indexKey,
			w: 8,
			h: 15,
			i: Date.now(),
			common: data,
		})
	}

	//缩放事件
	const setResize = (i: number, newH: number, newW: number, newHPx: number, newWPx: number) => {
		const indexKey = componentList.value.findIndex((item) => item.i == i)
		const up = (e) => {
			if (componentList.value[indexKey]) {
				componentList.value[indexKey].refreshKey = Math.random()
			}
			window.removeEventListener('mouseup', up)
		}
		window.addEventListener('mouseup', up)
	}

	return {
		componentIndex,
		componentList,
		widgetFormConfig,
		setActive,
		deleteDesign,
		setWidgetFormConfig,
		setDrop,
		setResize,
		setDesignData,
	}
})
